package com.blog.controller;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.blog.model.Post;
import com.blog.service.BlogService;

@Controller
@RequestMapping("/")
public class BlogController {
    private static final Logger logger = LoggerFactory.getLogger(BlogController.class);

    @Autowired
    private BlogService blogService;

    @PostConstruct
    public void init() {
        // Add sample posts
        if (blogService.getAllPosts().isEmpty()) {
            Post post1 = new Post();
            post1.setTitle("Welcome to My Blog");
            post1.setContent("This is a personal blog system built with Spring Boot.\n\n" +
                    "## Features\n\n" +
                    "* Post publishing and management\n" +
                    "* Responsive design\n" +
                    "* Markdown support\n\n" +
                    "Thanks for visiting!");
            blogService.createPost(post1);

            Post post2 = new Post();
            post2.setTitle("Getting Started with Spring Boot");
            post2.setContent("Spring Boot is a framework that makes it easy to create Spring-powered applications...");
            blogService.createPost(post2);
        }
    }

    @GetMapping
    public String index(Model model) {
        logger.info("Accessing index page");
        try {
            model.addAttribute("posts", blogService.getAllPosts());
            return "index";
        } catch (Exception e) {
            logger.error("Error accessing index page: ", e);
            return "error";
        }
    }

    @GetMapping("/post/new")
    public String showPostForm(Model model) {
        logger.info("Accessing new post form page");
        try {
            model.addAttribute("post", new Post());
            logger.info("Successfully created new post form");
            return "post-form";
        } catch (Exception e) {
            logger.error("Error showing post form: ", e);
            return "error";
        }
    }

    @PostMapping("/post/create")
    public String createPost(@ModelAttribute Post post) {
        logger.info("Creating new post with title: {}", post.getTitle());
        try {
            blogService.createPost(post);
            logger.info("Successfully created post");
            return "redirect:/";
        } catch (Exception e) {
            logger.error("Error creating post: ", e);
            return "error";
        }
    }

    @GetMapping("/post/{id}")
    public String getPost(@PathVariable Long id, Model model) {
        logger.info("Accessing post with id: {}", id);
        try {
            Post post = blogService.getPostById(id)
                .orElseThrow(() -> new RuntimeException("Post not found"));
            model.addAttribute("post", post);
            return "post";
        } catch (Exception e) {
            logger.error("Error getting post: ", e);
            return "error";
        }
    }

    @DeleteMapping("/post/{id}/delete")
    public String deletePost(@PathVariable Long id) {
        logger.info("Deleting post with id: {}", id);
        try {
            Post post = blogService.getPostById(id)
                .orElseThrow(() -> new RuntimeException("Post not found"));
            blogService.deletePost(id);
            logger.info("Successfully deleted post: {}", post.getTitle());
            return "redirect:/";
        } catch (Exception e) {
            logger.error("Error deleting post: ", e);
            return "error";
        }
    }

    @GetMapping("/post/{id}/edit")
    public String showEditForm(@PathVariable Long id, Model model) {
        logger.info("Accessing edit form for post with id: {}", id);
        try {
            Post post = blogService.getPostById(id)
                .orElseThrow(() -> new RuntimeException("Post not found"));
            model.addAttribute("post", post);
            return "post-edit";
        } catch (Exception e) {
            logger.error("Error showing edit form: ", e);
            return "error";
        }
    }

    @PutMapping("/post/{id}/update")
    public String updatePost(@PathVariable Long id, @ModelAttribute Post post) {
        logger.info("Updating post with id: {}", id);
        try {
            Post existingPost = blogService.getPostById(id)
                .orElseThrow(() -> new RuntimeException("Post not found"));
            existingPost.setTitle(post.getTitle());
            existingPost.setContent(post.getContent());
            blogService.createPost(existingPost);
            logger.info("Successfully updated post: {}", post.getTitle());
            return "redirect:/post/" + id;
        } catch (Exception e) {
            logger.error("Error updating post: ", e);
            return "error";
        }
    }

    // 添加错误页面处理
    @GetMapping("/error")
    public String handleError() {
        return "error";
    }
}